/**
 * @author qiuny
 * @description 历史记录插件类
 * @class
 * @see {@link CoverEditor}
 */

import { fabric } from "fabric";
import "fabric-history";

class HistoryPlugin {
    static apis = ["undo", "redo"];
    static events = ["historyUpdate"];

    constructor(canvas, editor) {
        this.canvas = canvas;
        this.editor = editor;
        
        this.hotkeys = ["ctrl+z", "ctrl+shift+z", "⌘+z", "⌘+shift+z"];
        fabric.Canvas.prototype._historyNext = () => {
            return this.editor.getJson();
        };

        this._init();
    }
    _init() {
        this.canvas.on("history:append", () => {
            this.historyUpdate();
        })
    }
    historyUpdate() {
        const { historyUndo, historyRedo } = this.canvas;
        // 触发后将数据实时传递给外部 historyUpdate 事件
        this.editor.emit("historyUpdate", historyUndo.length, historyRedo.length);
    }

    // 导入模板之后，清理 History 缓存
    hookImportAfter() {
        console.log('hookImportAfter1');
        this.canvas.clearHistory();
        this.historyUpdate();
        return Promise.resolve();
    }

    undo() {
        // fix 历史记录退回到第一步时，画布区域可被拖拽
        if (this.canvas.historyUndo.length === 1) {
            this.editor.clear();
            this.canvas.clearHistory();
            return;
        }
        this.canvas.undo();
        this.historyUpdate();
    }

    redo() {
        this.canvas.redo();
        this.historyUpdate();
    }
    // 快捷键扩展回调
    hotkeyEvent(eventName, evt) {
        if (evt.type === "keydown") {
            switch (eventName) {
                case "ctrl+z":
                case "⌘+z":
                    this.undo();
                    break;
                case "ctrl+shift+z":
                case "⌘+shift+z":
                    this.redo();
                    break;
            }
        }
    }

    destroy() {
        console.log('HistoryPlugin destroy');
    }
}

export default HistoryPlugin;
